<?php

namespace app\api\controller;

use app\api\model\Code;
use app\api\model\YaoqingRecords as Income;
use think\Db;
use app\api\model\WithdrawStyle;
use app\api\model\ConfigSystem as Config;
use Vectorface\Whip\Whip;
use app\service\UserRepeat;
use app\service\UserWarn;
use app\service\RedisQueue;

class Withdraw extends Common
{
    public function lists()
    {
        $result = Db::name('withdraw')->where(['userid' => $this->member['id'], 'state' => ['neq', 2]])->value('id');

        $first = $result ? 0 : 1;

        $where = $first ? ['id' => ['gt', 0]] : ['is_first' => 0];
        
        // 查询用户是否为超级提现人
        $is_super = Db::name('user_supertx')->where(['userid' => $this->member['id']])->find();

        // 提现方式权限控制：
        // - 普通用户只能看到 supertx=0 的提现方式
        // - 超级提现人可以看到所有提现方式（包括 supertx=1 的特殊方式）
        if (!$is_super) {
            $where['supertx'] = 0;
        }

        $data = WithdrawStyle::all(function($query) use ($where) {
            $query->field('is_first, sort, create_time', true)->where($where)->order('sort desc');
        });
        $config = Config::index('withdraw');

        foreach ($data as $key => $item) {
            $data[$key]['icon'] = changeUrl($item['icon']);
            $data[$key]['price'] =  sprintf("%.0f", $item['price']);
            $data[$key]['money'] =  sprintf("%.0f", $item['money']);
            $data[$key]['shouxu_wx'] =  number_format($data[$key]['price'] * $config['shouxu_wx'], 2);
            $data[$key]['shouxu_zfb'] =  number_format($data[$key]['price'] * $config['shouxu_zfb'], 2);
            $data[$key]['shouxu_bank'] =  number_format($data[$key]['price'] * $config['shouxu_bank'], 2);
        }

        return $this->pass($data);
    }

    public function payments()
    {
        $config = Config::index('withdraw');
        $paymethods = [
            'transfer_for_bank'=>['label'=>'银行卡', 'method'=>2],
            'transfer_for_wechat'=>['label'=>'微信', 'method'=>0],
            'transfer_for_alipay'=>['label'=>'支付宝', 'method'=>1],
        ];
        $payment = [];
        foreach ($paymethods as $key => $value) {
            $payment[] = ['label'=>$value['label'], 'method'=>$value['method'], 'status'=>(int)$config[$key]];
        }
        return $this->pass($payment);
    }

    public function submit()
    {
        $hour = date('H');
        $minute = date('i');
        $timenow = time();

        // if ($timenow >= strtotime('2023-09-28') && $timenow <= strtotime('2023-09-30')) {
        //     return $this->miss('中秋假期期间暂不开放提现');
        // }
        // $w = date('w');
        // if ($w == 6) {
        //     return $this->miss('周六暂不开放提现');
        // }

        /*if ($hour >= 17) {
            return $this->miss('提现时间00:00 - 17:00');
        }*/


        $config_withdrawtime = Config::index('withdrawtime');


        if (intval($config_withdrawtime['withdraw_minute']) == 0 && $hour < $config_withdrawtime['withdraw_hour']) {
            return $this->miss('提现时间'.$config_withdrawtime['withdraw_hour'].':00 - 23:59');
        }

        if ($hour < $config_withdrawtime['withdraw_hour'] || ($hour == $config_withdrawtime['withdraw_hour'] && $minute < intval($config_withdrawtime['withdraw_minute']))) {
            return $this->miss('提现时间'.$config_withdrawtime['withdraw_hour'].':'.$config_withdrawtime['withdraw_minute'].' - 23:59');
        }
        
        if (!isset($this->params['paypwd']) && !isset($this->params['code'])) {
            return $this->miss('提现密码错误');
        }

        if (isset($this->params['paypwd'])) {
            if (!$this->member['paypwd']) {
                return $this->miss('尚未设置提现密码');
            }
    
            if(!password_verify($this->params['paypwd'], $this->member['paypwd'])) {
                return $this->miss('提现密码错误');
            }
        }

        $id = $this->params['id'];
        $paymethod = $this->params['method'];

        $style = Db::name('withdraw_style')->find($id);
        if (!$style) return $this->miss('选择有误');

        $config = Config::index('', 'rate');
        if($style['money'] * $config['rate'] < $style['price']){
            return $this->miss('提现异常');
        }
        // usleep(500000);

        $user = $this->member;

        if($user['realname_auth']!=2){
            return $this->miss('请先实名认证，再进行提现操作');
        }
        $tixianlimit = Db::name('withdraw_limit')->find($user['id']);
        if($tixianlimit){
            return $this->miss('提现已被拒绝');
        }



        $config = Config::index('withdraw');

        $paymethodsShouxu = ['shouxu_wx', 'shouxu_zfb', 'shouxu_bank'];
        $shouxu_rate = $config[$paymethodsShouxu[$paymethod]];

        $shouxu = $shouxu_rate * $style['price'];
        $paymethods = ['transfer_for_wechat', 'transfer_for_alipay', 'transfer_for_bank'];
        if(!$config[$paymethods[$paymethod]]){
            return $this->miss('提现渠道未开放');
        }



        $frozen = Db::name('wallet_frozen')->where(['user_id'=>$user['id']])->find();
        if($frozen){
            $user['score'] = $user['score'] - $frozen['value'];
        }

        if ($user['score'] < ($style['price'] + $shouxu)) {
            $msg = '账户余额不足';

            if ($shouxu > 0) {
                $msg .= ' (包含手续费：'.$shouxu.')';
            }
            return $this->miss($msg);
        }
    
        if (isset($this->params['code'])) {
            $result = Code::verifyCode($this->member['phone'], $this->params['code']);
            if ($result['code'] == 400) {
                return $this->miss($result['msg']);
            }
        }

        $content = '提现申请';
        if ($shouxu > 0) {
            $content .= ' (手续费：'.$shouxu.')';
        }

        $total = $style['price'] + $shouxu;
        $total = changefloor($total);

        $realname = Db::name('user_certification')->where(['types' => 1, 'user_id' => $this->member['id']])->value('data2');
        if($realname){
            if ($realname != $user['zhifuname'] && $realname != $user['bank_user_name']) {
                return $this->miss('提现账户姓名与实名信息姓名不一致');
            }
        // } else {
            // return $this->miss('未填写名字，请联系客服填写');
        }


        $withdrawCount = Db::name('withdraw')->master()->where(['userid'=>$this->member['id']])->whereTime('create_time', 'today')->sum('money');
        if($paymethod == 1){
            $withdrawAllCount = Db::name('withdraw')->master()->where(['paymethod'=>1])->whereTime('create_time', 'today')->sum('money');
            $data = ['name' => $user['zhifuname'], 'account' => $user['zhifucount']];
            if ($user['is_banned'] && strtotime($user['banned_end_time']) > time()) {
                if($withdrawCount + $style['money'] > $config['banned_max']){
                    return $this->miss('今日提现已达上限');
                }
            }
            if($withdrawAllCount + $style['money'] > $config['withdraw_alipay_max']){
                return $this->miss('支付宝提现今日满额，请使用微信提现');
            }
        }elseif($paymethod == 2){
            if(!$user['bank'] || !$user['bank_user_name'] || !$user['bank_number']){
                return $this->miss('未绑定银行卡');
            }
            $data = ['name' => $user['bank'], 'bank_user_name' => $user['bank_user_name'], 'account' => $user['bank_number']];
        }else{
            if(!$user['wechat']){
                return $this->miss('未绑定微信');
            }
            if($withdrawCount + $style['money'] >= 200){
                return $this->miss('微信每日提现上限为195');
            }

            if(isset($config['transfer_for_wechat_type']) && $config['transfer_for_wechat_type'] == 1){
                $gzhopenid = Db::name('wechat_union')->where(['user_id'=>$user['id']])->value('wxgzh_openid');
                if(!$gzhopenid){
                    $config_wechat = Config::index('wechat');
                    return json_encode(['code'=>201, 'msg'=>'请先关注【那蓝之恋1】微信公众号绑定账号', 'qrcode'=>$config_wechat['gzh_qrocde']]);
                }
                $data = ['name' => $user['zhifuname'], 'account' => $gzhopenid, 'type'=>1];
            }else{
                if (strpos($user['wechat'], 'oDm') === 0) return $this->miss('请下载新版APP重新绑定微信后再尝试提现');
                $data = ['name' => $user['zhifuname'], 'account' => $user['wechat'], 'type'=>0];
            }
        }

        try {
            $data['ip'] = (new Whip())->getValidIpAddress();
        }catch (Exception $e) {
            
        }
        $account = $data['account'];

        $data = json_encode($data, JSON_UNESCAPED_UNICODE);

        $paymethodstext = ['微信', '支付宝', '银行卡'];
        
        $withdrawoftoday = Db::name('withdraw')->master()->where(['userid'=>$this->member['id']])->whereTime('create_time', 'today')->find();
        if($withdrawoftoday && $withdrawoftoday['paymethod'] != $paymethod){
            return $this->miss('每天只允许选择一种提现方式，请选择提现到'.$paymethodstext[$withdrawoftoday['paymethod']]);
        }

        $paymethodslimit = [120000, 99999999, 99999999];

        $withdrawoftodaycount = Db::name('withdraw')->master()->where(['paymethod'=>$paymethod])->whereTime('create_time', 'today')->sum('money');
        if($withdrawoftodaycount >= $paymethodslimit[$paymethod]){
            return $this->miss($paymethodstext[$paymethod] . '当天提现已满，可选择' . $paymethodstext[$paymethod == 0 ? 1 : 0]);
        }

        // 启动事务
        Db::startTrans();
        try {
            $state = Income::index($this->member['id'], 0, $total, $content, 1, '', 1);

            $order_no = uniqid('w'.$this->member['id'].'n');
        
            $insert = Db::name('withdraw')->insert([
                "userid" => $this->member['id'],
                "paymethod" => $paymethod,
                "money" => $style['money'],
                'price' => $style['price'],
                'shouxu' => $shouxu,
                'shouxu' => $shouxu,
                'data' => $data,
                'create_time' => time(),
                'update_time' => time(),
                'expire_time' => time() + 60 * 60 * 24 * 14,
                'order_no'=>$order_no
            ]);

            UserRepeat::InsertS($this->member['id'], 'zhifucounts', $account);
            UserWarn::CheckWarn($this->member['id'], '发起提现');


            if($state && $insert){
                // 提交事务
                Db::commit();
            }else{
                throw new \think\Exception('提现异常，请重试', 100006);
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();

            return $this->miss($e->getMessage());
        }

        return $this->pass('申请已提交');
    }

    public function records()
    {
        $page = input('page/d', 1);
        $pagesize = input('pagesize/d', 10);
        $records = Db::name('withdraw')
                    ->where(['userid'=>$this->member['id']])
                    ->page($page)
                    ->limit($pagesize)
                    ->select();

        $state = ['审核中','提现成功','提现失败'];
        $paymethod = ['微信','支付宝', '银行卡'];
        foreach ($records as &$value) {
            $value['data'] = json_decode($value['data'], true);
            $value['state_text'] = $state[$value['state']];
            $value['paymethod_text'] = $paymethod[$value['paymethod']];
            $value['create_time'] = date('Y-m-d H:i', $value['create_time']);
            $value['update_time'] = date('Y-m-d H:i', $value['update_time']);
        }
        return $this->pass($records);
    }
}
